/**
 * 
 */
package com.ms.service.module.datacenterlite;

import java.util.ArrayList;
import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ms.game.common.container.BasicSettingUtil;
import com.ms.game.common.container.GameTypeInfo;
import com.ms.game.slot.base.message.SGmtoolCleanDoormanSeatStatusRequest;
import com.xpec.c4.db.dao.PlayerKeepSeatDAO;
import com.xpec.c4.db.model.PlayerKeepSeatClearLogModel;
import com.xpec.c4.message.MessageTypes;
import com.xpec.c4.service.group.transportlayer.GroupMessage;
import com.xpec.c4.service.message.MessageAction;
import com.xpec.c4.service.module.task.TaskAsyncCommand;

/**
 * 清除座位保留的異步處理 task
 * 
 * @author TW15010
 */
public class KeepSeatClearAsync extends TaskAsyncCommand {
	/** log4j object */
	private static final Log log = LogFactory.getLog(KeepSeatClearAsync.class);

	/**
	 * 執行 task 的 module
	 */
	private DataCenterLiteModule srcModule;

	@Override
	public void asyncExecute() throws Exception {
		// 取得要被清除保留狀態的座位資料清單
		ArrayList<PlayerKeepSeatClearLogModel> seatClearLogList = PlayerKeepSeatDAO.loadWaitClearKeepSeatData();

		// 處理完成，準備更新狀態的 model list
		ArrayList<PlayerKeepSeatClearLogModel> finishList = new ArrayList<PlayerKeepSeatClearLogModel>();

		for (PlayerKeepSeatClearLogModel model : seatClearLogList) {
			// 取得指定的遊戲 doorman module id
			GameTypeInfo info = BasicSettingUtil.getGameTypeInfo(model.getGameType());
			if (info == null) {
				if (log.isErrorEnabled()) {
					log.error("clear fail, game type " + model.getGameType() + " invalid.");
				}
				continue;
			}

			String doormanModuleId = info.getModuleId();

			// 送出清除座位要求給 doorman
			SGmtoolCleanDoormanSeatStatusRequest request = new SGmtoolCleanDoormanSeatStatusRequest();
			request.setGamename(model.getGameType());
			request.setHalltype(model.getHallType());
			request.setSeatid(model.getSeatId());
			request.setKeepDataPlayerId(model.getPlayerId());
			request.setOfflineKeep(model.isOfflineKeep());
			request.setFromDataCenterLite(true);

			GroupMessage msg = new GroupMessage();
			msg.setMessageType(MessageTypes.S_GMTOOL_CLEAN_DOORMAN_SEAT_STATUS);
			msg.setMessageContent(request);
			msg.setDestModuleID(doormanModuleId);
			MessageAction.sendGroupMessage(msg);

			model.setFinishTime(Calendar.getInstance());
			model.setStatus(PlayerKeepSeatClearLogModel.FINISH);
			finishList.add(model);
		}

		PlayerKeepSeatDAO.saveWaitClearKeepSeatData(finishList);
	}

	@Override
	public void execute() throws Exception {
		if (srcModule != null) {
			srcModule.onKeepSeatClearTimerTaskFinish();
		}
	}

	public DataCenterLiteModule getSrcModule() {
		return srcModule;
	}

	public void setSrcModule(DataCenterLiteModule srcModule) {
		this.srcModule = srcModule;
	}
}
